<?php

namespace App\Command\ResumeParsing\Service\ParsingSpecial;

use App\Service\FileHandler;
use EchoPHP\Facades\Log;

class ParsingLiepin extends ParsingSpecialXml {
    function __construct($helper) {
        parent::__construct($helper);
        $this->titleXpath = "//table[tr/td[contains(@style, 'solid #404040 2.25pt') and p[contains(@style, 'line-height:15.0pt')]]]";

        $this->get['template'] = function () {
            $this->listXPath("//templateTag[normalize-space()='templateTagName']");    //[contains(., 'templateTagName')][starts-with(normalize-space(), 'templateTagName')]
            $result = $this->xPath->query();
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['id'] = function () {
            $result = $this->xPath->query("//table/tr/td/p[starts-with(normalize-space(), '简历编号信息：')]//b");
            if ($result->length) return $this->formatTxt($result[0]->textContent);
            $result = $this->xPath->query("//table/tr/td[normalize-space()='简历编号：']/following-sibling::td[1]");
            if ($result->length) {
                $this->groupCache['oldVersion'] = true;
                return $this->formatTxt($result[0]->textContent);
            }
            return '';
        };

        $this->get['time'] = function () {
            $result = $this->xPath->query("//table/tr/td/p[starts-with(normalize-space(), '简历更新时间：')]//b");
            if ($result->length) return $this->formatTxt($result[0]->textContent);
            $result = $this->xPath->query("//table/tr/td[normalize-space()='最新登录：']/following-sibling::td[1]");
            if ($result->length) {
                $this->groupCache['oldVersion'] = true;
                return $this->formatTxt($result[0]->textContent);
            }
            return '';
        };

        $this->get['name'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='姓名：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['sex'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='性别：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<result>[男女])性?/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['nation'] = $this->tagNotExist;

        $this->get['identitycard'] = $this->tagNotExist;

        $this->get['mobile'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='手机号码：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['email'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='电子邮件：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['age'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='年龄：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['married'] = $this->tagNotExist;

        $this->get['politic'] = $this->tagNotExist;

        $this->get['degree'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='教育程度：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['industry'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='期望行业：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['position'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='期望职位：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['career'] = $this->tagNotExist;

        $this->get['major'] = $this->tagNotExist;

        $this->get['birthday'] = $this->tagNotExist;

        $this->get['workyear'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='工作年限：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['workarea'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='所在地：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['expectarea'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='期望地点：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['area'] = $this->tagNotExist;

        $this->get['salary'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='目前年薪：']]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            $resultText = $this->formatTxt($result[0]->textContent);
            $salary = $this->func->parseSalary($resultText, 'annual');
            if (count($salary)) {
                $this->helper->resumeInfo['salaryfrom'] = $salary['monthly']['begin'];
                $this->helper->resumeInfo['salaryend'] = $salary['monthly']['end'];
                //$this->helper->resumeInfo['salaryafrom'] = $salary['annual']['begin'];
                //$this->helper->resumeInfo['salaryaend'] = $salary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['expectsalary'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='期望年薪：']]/following-sibling::td[1]/p[1]");
            if ($result->length < 1) return '';
            $resultText = $this->formatTxt($result[0]->textContent);
            $expectsalary = $this->func->parseSalary($resultText, 'annual');
            if (count($expectsalary)) {
                $this->helper->resumeInfo['expectsalaryfrom'] = $expectsalary['monthly']['begin'];
                $this->helper->resumeInfo['expectsalaryend'] = $expectsalary['monthly']['end'];
                //$this->helper->resumeInfo['expectsalaryafrom'] = $expectsalary['annual']['begin'];
                //$this->helper->resumeInfo['expectsalaryaend'] = $expectsalary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['jobterm'] = $this->tagNotExist;

        $this->get['school'] = $this->tagNotExist;

        $this->get['nofocuse'] = function () {
            $result = $this->xPath->query("//table/tr/td[p//span[normalize-space()='勿推企业：']]/following-sibling::td[1]/p[2]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, 'space');
        };

        $this->get['workinfo'] = function () {
            $result = $this->xPath->query("//table/tr/td/p/b/span[normalize-space()='工作经历']/../../../../../following-sibling::table[1]/tr");
            if ($result->length < 1) return '';
            $data = array();
            $index = 0;
            foreach ($result as $tr) {
                if (count($this->xPath->query("td[contains(@style,'background:#EAEAEA')][1]", $tr)) && preg_match('/^(?<time>(?<!\d)(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))(?!\d))?)\s*(?<company>.*?)?$/u', $this->formatTxt($tr->textContent), $matches)) {
                    if (isset($item)) {
                        $item['comment'] = trim($item['comment']);
                        $data[] = $item;
                    }
                    $item = ['comment' => '', 'time' => $matches['time'] ?? '', 'company' => $matches['company'] ?? ''];
                    $tmp = $this->func->parseTimespan($item['time']);
                    $item['time_from'] = $tmp['begin'];
                    $item['time_end'] = $tmp['end'];
                    $index = 0;
                } elseif (!empty($item)) {
                    switch ($index) {
                        case 1:
                            $pArr = $this->xPath->query('td[2]/p', $tr);
                            foreach ($pArr as $p) {
                                $line = $this->formatTxt($p->textContent, TRUE);
                                if (($industry = $this->preg_get('/(?:\s*\|\s*|^\s*)公司行业\s*：\s*(?<result>.*)(?:\s*\||$)/u', $line))) {
                                    $item['industry'] = $industry;
                                    $line = preg_replace('/(?:\s*\|\s*|^\s*)公司行业\s*：\s*(?<result>.*)(?:\s*\||$)/u', '', $line);
                                }
                                $item['comment'] .= "\r\n" . $line;
                            }
                            break;
                        case 2:
                            if (preg_match('/^(?<duty>.*?)??\s*(?:(?<time>\d{4}\/\d{1,2}(?:\/\d{1,2})?\s*-\s*(?:\d{4}\/\d{1,2}(?:\/\d{1,2})?|至今))|(?<salary>\d+(?:\.\d+)?\s*[kw万]?\s*元?(?:\s*[-–—~～至到]\s*\d+(?:\.\d+)?\s*[kw万]?\s*元?)?\s*[\/每][^\r\n]?))?$/us', $this->formatTxt($tr->textContent), $matches)) {
                                $item['duty'] = !empty($matches['duty']) ? $this->formatTxt($matches['duty'], TRUE) : '';
                                $item['salary'] = !empty($matches['salary']) ? $this->formatTxt($matches['salary'], TRUE) : '';
                            }
                            break;
                        case 3:
                        case 4:
                            $tdArr = $this->xPath->query("td", $tr);
                            if (count($tdArr) > 1 && !preg_match('/^\s*工作职责和业绩：/u', $tr->textContent)) {
                                $arr = [];
                                foreach ($tdArr as $td) {
                                    if ($tmp = $this->formatTxt($td->textContent, true)) {
                                        if (empty($item['salary']) && ($salary = $this->preg_get('/^薪酬情况\s*：\s*(?<result>.*)$/u', $tmp))) {
                                            $item['salary'] = $salary;
                                        } else {
                                            $arr[] = $tmp;
                                        }
                                    }
                                }
                                if (count($arr)) $item['comment'] .= "\r\n" . implode(' | ', $arr);
                            } else {
                                $item['comment'] .= "\r\n" . $this->formatTxt($tr->textContent);
                            }
                            break;
                        default:
                            $item['comment'] .= "\r\n" . $this->formatTxt($tr->textContent);
                            break;
                    }
                }
                $index++;
            }
            if ($index > 1) {
                $item['comment'] = trim($item['comment']);
                $data[] = $item;
            }
            return $data;
        };

        $this->get['projectinfo'] = function () {
            $result = $this->xPath->query("//table/tr/td/p/b/span[normalize-space()='项目经历']/../../../../../following-sibling::table[1]/tr");
            if ($result->length < 1) return '';
            $boundary = $result[0]->attributes->getNamedItem('style')->value;
            $data = array();
            foreach ($result as $tr) {
                if (!$tr->attributes->getNamedItem('style') || $tr->attributes->getNamedItem('style')->value == $boundary) {
                    if (isset($item)) {
                        $item['comment'] = trim($item['comment']);
                        $data[] = $item;
                    }
                    $item = array('comment' => '');
                    $index = 0;
                }
                switch ($index) {
                    case 0:
                        if (preg_match('/^(?<time>(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~～到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))))\s*(?<project>.*?)$/us', $this->formatTxt($tr->textContent), $matches)) {
                            $item['time'] = $this->formatTxt($matches['time'], TRUE);
                            $item['project'] = $matches['project'];
                            $tmp = $this->func->parseTimespan($item['time']);
                            $item['time_from'] = $tmp['begin'];
                            $item['time_end'] = $tmp['end'];
                        }
                        break;
                    case 1:
                        $tmp = array_values(array_filter(array_map('trim', explode("\n", $this->formatTxt($tr->textContent)))));
                        if (count($tmp) == 2) {
                            $item['duty'] = $tmp[1];
                        }
                        break;
                    case 2:
                        $tmp = array_values(array_filter(array_map('trim', explode("\n", $tr->textContent))));
                        if (count($tmp) == 2) {
                            $item['company'] = $tmp[1];
                        }
                        break;
                    case 3:
                        $item['comment'] .= "\r\n" . $this->formatTxt($tr->textContent);
                        break;
                    case 4:
                        $item['comment'] .= "\r\n" . $this->formatTxt($tr->textContent);
                        break;
                    case 5:
                        $item['comment'] .= "\r\n" . $this->formatTxt($tr->textContent);
                        break;
                    default:
                        $item['comment'] .= "\r\n" . $this->formatTxt($tr->textContent);
                        break;
                }
                $index++;
            }
            if ($index > 1) {
                $item['comment'] = trim($item['comment']);
                $data[] = $item;
            }
            return $data;
        };

        $this->get['educationinfo'] = function () {
            $result = $this->getPart('教育经历', true);
            if (!count($result)) return [];

            $data = array();
            if (empty($this->groupCache['oldVersion'])) {
                $style = $result[0]->attributes->getNamedItem('style')->value;
                foreach ($result as $table) {
                    if (!isset($table->attributes) || !isset($table->attributes->getNamedItem('style')->value) || $table->attributes->getNamedItem('style')->value != $style) break;

                    $item = array('comment' => '');
                    $trArr = $this->xPath->query('tr', $table);
                    if (!count($trArr)) continue;

                    if (preg_match('/^(?<school>.*?)??(?:\s*（?\s*(?<time>(?<!\d)(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))(?!\d))?)\s*）?)?$/u', $this->formatTxt($trArr[0]->textContent, true), $matches)) {
                        $item['school'] = $matches['school'] ?? '';
                        $item['time'] = $matches['time'] ?? '';
                        $tmp = $this->func->parseTimespan($item['time']);
                        $item['time_from'] = $tmp['begin'];
                        $item['time_end'] = $tmp['end'];
                    }
                    if (!empty($trArr[1])) {
                        $tmp = array_values(array_filter(array_map('trim', explode("\n", $trArr[1]->textContent))));
                        if (count($tmp) == 3) {
                            $item['major'] = $this->preg_get('/(?<=专业：).*(?=\s|$)/u', $tmp[0]) ?: '';
                            $item['degree'] = $this->preg_get('/(?<=学历：).*(?=\s|$)/u', $tmp[1]) ?: '';
                            $item['comment'] .= trim($tmp[2]);
                        }
                    }
                    $item['comment'] = trim($item['comment']);
                    $data[] = $item;
                }
            }
            if (empty($data)) {
                $trArr = $this->xPath->query('tr', $result[0]);
                if (!count($trArr)) return [];
                foreach ($trArr as $tr) {
                    $item = [];
                    $node = $this->xPath->query('td[1]/p/b[1]', $tr);
                    if (count($node)) $item['school'] = $this->formatTxt($node[0]->textContent);
                    $node = $this->xPath->query('td[1]/p/b[2]', $tr);
                    if (count($node)) {
                        $item['time'] = $this->formatTxt($node[0]->textContent);
                        $tmp = $this->func->parseTimespan($item['time']);
                        $item['time_from'] = $tmp['begin'];
                        $item['time_end'] = $tmp['end'];
                    }
                    $node = $this->xPath->query('td[2]', $tr);
                    if (count($node)) $item['major'] = $this->formatTxt($node[0]->textContent);
                    $node = $this->xPath->query('td[3]', $tr);
                    if (count($node)) $item['degree'] = $this->formatTxt($node[0]->textContent);
                    $data[] = $item;
                }
            }
            return $data;
        };

        $this->get['skillinfo'] = function () {
            $result = $this->xPath->query("//table/tr/td/p/b/span[normalize-space()='语言能力']/../../../../../following-sibling::table[1]");
            if ($result->length < 1) return '';
            return '语言能力：' . $this->formatTxt($result[0]->textContent);
        };

        $this->get['awardinfo'] = $this->tagNotExist;

        $this->get['commentinfo'] = function () {
            $result = $this->xPath->query("//table/tr/td/p/b/span[normalize-space()='自我评价']/../../../../../following-sibling::table[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['otherinfo'] = function () {
            $result = $this->xPath->query("//table/tr/td/p/b/span[normalize-space()='附加信息']/../../../../../following-sibling::table[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['avatar'] = function () {
            try {
                $tables = $this->getPart('个人信息', true, 'table');
                if (!count($tables)) return '';
                $result = $this->xPath->query("descendant::img[1]/@src", $tables[0]);
                if (!count($result) || empty($url = $result[0]->textContent) ||     //猎聘有一系列预置头像，没有导入价值
                    preg_match('/^https:\/\/image0\.lietou-static\.com\/normal\/55557f[a-z1-9]{2}28ee44a8919620[a-z1-9]{2}01a\.gif$/i', $url)) return '';

                return ['url' => $url, 'name' => basename($url)];
            } catch (\Exception $e) {
                Log::error(e_dump($e), ['avatar' => $url ?? ''], 'cmd');
                return '';
            }
        };
    }
}
